"""
    发送验证邮件
"""
from random import Random

from users.models import EmailVerifyRecord
from django.core.mail import send_mail

from gmooc.settings import EMAIL_FROM


# 短信验证码记录
def send_register_email(email, send_type="register"):
    # 实例化对象
    email_record = EmailVerifyRecord()
    # 生成随机字符串
    code = generate_random_str(16)
    # 为新对象赋值
    email_record.code = code
    email_record.email = email
    email_record.send_type = send_type
    # 将新内容保存到数据库
    email_record.save()

    email_title = ""
    email_body = ""

    if send_type == "register":
        email_title = "慕学在线网注册激活链接"
        email_body = "请点击下方链接激活你的账号：http://127.0.0.1:8000/active/{0}".format(code)
        # 发送验证邮件
        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        # 发送成功为 True 否则为 False
        if (send_status):
            print("----- 注册邮件发送成功 -----")

    elif send_type == "forget":
        email_title = "慕学在线网密码重置链接"
        email_body = "请点击下方链接重置你的密码：http://127.0.0.1:8000/reset/{0}".format(code)
        # 发送验证邮件
        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        # 发送成功为 True 否则为 False
        if (send_status):
            print("----- 重置邮件发送成功 -----")


# 生成随机字符串
def generate_random_str(randomlength=8):
    str = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        str += chars[random.randint(0, length)]
    return str
